package com.neusoft.nep.supervise.controller;

import com.neusoft.nep.common.Dialog;
import com.neusoft.nep.common.FileUtils;
import com.neusoft.nep.common.ViewSwitcher;
import com.neusoft.nep.supervise.entity.User;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;

import java.io.*;
import java.net.URL;
import java.util.*;


public class UserRegisterViewController implements Initializable {
    @FXML
    private Button btn_back;
    @FXML
    private TextField txt_phoneNumber;
    @FXML
    private TextField txt_userName;
    @FXML
    private PasswordField txt_password;
    @FXML
    private PasswordField txt_password2;
    @FXML
    private CheckBox CheckBox_male;
    @FXML
    private CheckBox CheckBox_female;
    @FXML
    private TextField txt_birthday;

    public UserRegisterViewController() {
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 设置 CheckBox 的监听器，避免同时选中
        CheckBox_male.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                CheckBox_female.setSelected(false);
            }
        });

        CheckBox_female.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                CheckBox_male.setSelected(false);
            }
        });
    }

    public void saveUser() {
        String phoneNumber = txt_phoneNumber.getText();
        String userName = txt_userName.getText();
        String password = txt_password.getText();
        String password2 = txt_password2.getText();
        String birthday = txt_birthday.getText();
        if (!password2.equals(password)) {
            Dialog.showErrorDialog("用户注册", "密码输入不一致");
            return;
        }
        String gender = "";
        if (CheckBox_male.isSelected()) {
            gender = "男";
        } else if (CheckBox_female.isSelected()) {
            gender = "女";
        } else {
            Dialog.showErrorDialog("用户注册", "请选择性别");
            return;
        }
        User u1 = new User(phoneNumber, userName, password, gender, birthday);

        Map<String, User> userMap = FileUtils.readMapObject("user.txt");
        userMap.put(u1.getPhoneNumber(), u1);
        //构建一个文件输出流
        FileUtils.writeMapObject("user.txt", userMap);
        Dialog.showDialog("用户注册", "注册成功");
    }

    public void back() throws IOException {
        ViewSwitcher.switchView(btn_back, "../supervise/view/UserLoginView.fxml");
    }
}
